package com.aimosheng.main.activity;

import android.content.Intent;
import android.net.Uri;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.aimosheng.common.utils.ScreenDimenUtil;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.braintreepayments.api.BraintreeFragment;
import com.braintreepayments.api.PayPal;
import com.braintreepayments.api.models.PayPalRequest;
import com.aimosheng.common.CommonAppConfig;
import com.aimosheng.common.Constants;
import com.aimosheng.common.HtmlConfig;
import com.aimosheng.common.activity.AbsActivity;
import com.aimosheng.common.activity.WebViewActivity;
import com.aimosheng.common.bean.CoinBean;
import com.aimosheng.common.bean.CoinPayBean;
import com.aimosheng.common.custom.ItemDecoration;
import com.aimosheng.common.event.CoinChangeEvent;
import com.aimosheng.common.http.CommonHttpConsts;
import com.aimosheng.common.http.CommonHttpUtil;
import com.aimosheng.common.http.HttpCallback;
import com.aimosheng.common.interfaces.OnItemClickListener;
import com.aimosheng.common.pay.PayCallback;
import com.aimosheng.common.pay.PayPresenter;
import com.aimosheng.common.pay.paypal.BraintreeUtils;
import com.aimosheng.common.utils.RouteUtil;
import com.aimosheng.common.utils.StringUtil;
import com.aimosheng.common.utils.ToastUtil;
import com.aimosheng.common.utils.WordUtil;
import com.aimosheng.main.R;
import com.aimosheng.main.adapter.CoinAdapter;
import com.aimosheng.main.adapter.CoinPayAdapter;
import com.mob.adsdk.AdSdk;
import com.scwang.smartrefresh.layout.util.DensityUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

/**
 * Created by cxf on 2018/10/23.
 * 充值
 */
@Route(path = RouteUtil.PATH_COIN)
public class MyCoinActivity extends AbsActivity implements OnItemClickListener<CoinBean>, View.OnClickListener, BraintreeUtils.IPayResultListener {

    private static final String TAG = "MyCoinActivity";
    private SwipeRefreshLayout mRefreshLayout;
    private RecyclerView mRecyclerView;
    private RecyclerView mPayRecyclerView;
    private CoinAdapter mAdapter;
    private CoinPayAdapter mPayAdapter;
    private TextView mBalance;
    private long mBalanceValue;
    private boolean mFirstLoad = true;
    private PayPresenter mPayPresenter;
    private String mCoinName;
    private boolean mPaypalIsSandbox;//paypal支付是否为沙盒模式
    private String mEnvironment = "";//支付环境
    private String mPaypalClientId = "";
    private ViewGroup mContainer;
    private AdSdk.BannerAd mBannerAd;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_coin;
    }

    @Override
    protected void main() {
        setTitle(WordUtil.getString(R.string.charge));
        mContainer = findViewById(R.id.container); //【重要】container 必须是 RelativeLayout，否则会有部分广告展示不全
        mRefreshLayout = findViewById(R.id.refreshLayout);
        mRefreshLayout.setColorSchemeResources(R.color.global);
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
//                if (mAdapter != null) {
//                    mAdapter.mCheckedPosition = -1;
//                }

                loadData();
            }
        });
        mCoinName = CommonAppConfig.getInstance().getCoinName();
        mRecyclerView = findViewById(R.id.recyclerView);
        mRecyclerView.setHasFixedSize(true);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, 3, GridLayoutManager.VERTICAL, false);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (position == 0) {
                    return 3;
                }
                return 1;
            }
        });
        mRecyclerView.setLayoutManager(gridLayoutManager);
        ItemDecoration decoration = new ItemDecoration(mContext, 0x00000000, 5, 20);
        decoration.setOnlySetItemOffsetsButNoDraw(true);
        mRecyclerView.addItemDecoration(decoration);
        mAdapter = new CoinAdapter(mContext, mCoinName);
        mAdapter.setOnItemClickListener(this);
        mRecyclerView.setAdapter(mAdapter);
        findViewById(R.id.btn_tip).setOnClickListener(this);
        View headView = mAdapter.getHeadView();
        TextView coinNameTextView = headView.findViewById(R.id.coin_name);
        coinNameTextView.setText(String.format(WordUtil.getString(R.string.wallet_coin_name), mCoinName));
        mBalance = headView.findViewById(R.id.coin);
        mPayRecyclerView = headView.findViewById(R.id.pay_recyclerView);
        ItemDecoration decoration2 = new ItemDecoration(mContext, 0x00000000, 14, 10);
        decoration2.setOnlySetItemOffsetsButNoDraw(true);
        mPayRecyclerView.addItemDecoration(decoration2);
        mPayRecyclerView.setLayoutManager(new GridLayoutManager(mContext, 3, GridLayoutManager.VERTICAL, false));
        mPayAdapter = new CoinPayAdapter(mContext);
        mPayAdapter.setOnItemClickListener(new OnItemClickListener<CoinPayBean>() {
            @Override
            public void onItemClick(CoinPayBean bean, int position) {
                //选择了PayPal支付方式,充值货币显示美元
                if (mAdapter != null) {
                    mAdapter.updatePayType(bean.getId());
                }
            }
        });
        mPayRecyclerView.setAdapter(mPayAdapter);
        mPayPresenter = new PayPresenter(this);
        mPayPresenter.setServiceNameAli(Constants.PAY_BUY_COIN_ALI);
        mPayPresenter.setServiceNameWx(Constants.PAY_BUY_COIN_WX);
        mPayPresenter.setAliCallbackUrl(HtmlConfig.ALI_PAY_COIN_URL);
        mPayPresenter.setPayCallback(new PayCallback() {
            @Override
            public void onSuccess() {
                if (mPayPresenter != null) {
                    mPayPresenter.checkPayResult();
                }
            }

            @Override
            public void onFailed() {

            }
        });
        EventBus.getDefault().register(this);
        BraintreeUtils.setPayResultListener(this);
        destroyBannerAd();
        loadBannerAd();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mFirstLoad) {
            mFirstLoad = false;
            loadData();
        }
    }

    private void loadData() {
        CommonHttpUtil.getBalance(new HttpCallback() {
            @Override
            public void onSuccess(int code, String msg, String[] info) {
                if (code == 0 && info.length > 0) {
                    JSONObject obj = JSON.parseObject(info[0]);
                    String coin = obj.getString("coin");
                    mBalanceValue = Long.parseLong(coin);
                    mBalance.setText(coin);
                    List<CoinPayBean> payList = JSON.parseArray(obj.getString("paylist"), CoinPayBean.class);
                    if (mPayAdapter != null) {
                        mPayAdapter.setList(payList);
                    }
                    List<CoinBean> list = JSON.parseArray(obj.getString("rules"), CoinBean.class);
                    if (mAdapter != null) {
                        mAdapter.setList(list);
                    }
                    mPayPresenter.setBalanceValue(mBalanceValue);
                    mPayPresenter.setAliPartner(obj.getString("aliapp_partner"));
                    mPayPresenter.setAliSellerId(obj.getString("aliapp_seller_id"));
                    mPayPresenter.setAliPrivateKey(obj.getString("aliapp_key"));
                    mPayPresenter.setWxAppID(obj.getString("wx_appid"));
                }
            }

            @Override
            public void onFinish() {
                if (mRefreshLayout != null) {
                    mRefreshLayout.setRefreshing(false);
                }
            }
        });
    }

    private String mBrantreeOrderId;
    private String mBrantreeMoney;

    @Override
    public void onItemClick(final CoinBean bean, int position) {
        if (mPayPresenter == null) {
            return;
        }
        if (mPayAdapter == null) {
            ToastUtil.show(R.string.wallet_tip_5);
            return;
        }
        if (Constants.PAY_TYPE_PAYPAL.equals(mPayAdapter.getPayType())) {
            mBrantreeMoney = bean.getMoney();
            CommonHttpUtil.getPaypalOrder(bean.getId(), bean.getPaypalCoin(), mBrantreeMoney, new HttpCallback() {
                @Override
                public void onSuccess(int code, String msg, String[] info) {
                    JSONObject obj = JSON.parseObject(info[0]);
                    mBrantreeOrderId = obj.getString("orderid");
                    getBrantreeToken(mBrantreeMoney);
                }
            });
        } else if (Constants.PAY_TYPE_ALI_H5.equals(mPayAdapter.getPayType())) {
            final String money = bean.getMoney();
            String orderParams = StringUtil.contact(
                    "&uid=", CommonAppConfig.getInstance().getUid(),
                    "&money=", money,
                    "&changeid=", bean.getId(),
                    "&coin=", bean.getCoin());
            CommonHttpUtil.getAliOrderH5(StringUtil.contact(Constants.PAY_BUY_COIN_ALI_H5, orderParams), new HttpCallback() {
                @Override
                public void onSuccess(int code, String msg, String[] info) {
                    if (code == 0 && info.length > 0) {
                        JSONObject obj = JSON.parseObject(info[0]);
                        String href = obj.getString("href");
                        try {
                            Intent intent = new Intent();
                            intent.setAction(Intent.ACTION_VIEW);
                            intent.setData(Uri.parse(href));
                            startActivity(intent);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        } else {
            String money = bean.getMoney();
            String goodsName = StringUtil.contact(bean.getCoin(), mCoinName);
            String orderParams = StringUtil.contact(
                    "&uid=", CommonAppConfig.getInstance().getUid(),
                    "&money=", money,
                    "&changeid=", bean.getId(),
                    "&coin=", bean.getCoin());
            mPayPresenter.pay(mPayAdapter.getPayType(), money, goodsName, orderParams);
        }
    }

    private void getBrantreeToken(final String money) {
        CommonHttpUtil.getPayToken(new HttpCallback() {
            @Override
            public void onSuccess(int code, String msg, String[] info) {
                if (code == 0 && info.length > 0) {
                    JSONObject jsonObject = JSON.parseObject(info[0]);
                    String braintreeToken = jsonObject.getString("braintreeToken");
                    if (TextUtils.isEmpty(braintreeToken)) {
                        ToastUtil.show(WordUtil.getString(R.string.pay_pay_not));
                        return;
                    }
                    setupBraintree(money, braintreeToken);
                } else {
                    ToastUtil.show(msg);
                }
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCoinChangeEvent(CoinChangeEvent e) {
        if (mBalance != null) {
            mBalance.setText(e.getCoin());
        }
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.btn_tip) {
            WebViewActivity.forward(mContext, HtmlConfig.CHARGE_PRIVCAY);
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        CommonHttpUtil.cancel(CommonHttpConsts.GET_BALANCE);
        CommonHttpUtil.cancel(CommonHttpConsts.GET_ALI_ORDER);
        CommonHttpUtil.cancel(CommonHttpConsts.GET_WX_ORDER);
        if (mRefreshLayout != null) {
            mRefreshLayout.setOnRefreshListener(null);
        }
        mRefreshLayout = null;
        if (mPayPresenter != null) {
            mPayPresenter.release();
        }
        mPayPresenter = null;
        super.onDestroy();
        destroyBannerAd();
    }





    public void setupBraintree(String money, String token) {
        PayPalRequest request = new PayPalRequest(money)
                .currencyCode("USD")
                .intent(PayPalRequest.INTENT_SALE);
        BraintreeFragment mInitFragment = BraintreeUtils.init(this, token);
        if (mInitFragment != null) {
            PayPal.requestOneTimePayment(mInitFragment, request);
        } else {
            ToastUtil.show(WordUtil.getString(R.string.pay_pay_isure));
        }
    }

    @Override
    public void paySuccess(String nonce) {
        payResult(nonce);
    }

    private void payResult(String nonce) {
        CommonHttpUtil.updatePaymentStatus(mBrantreeOrderId, mBrantreeMoney, nonce, new HttpCallback() {
            @Override
            public void onSuccess(int code, String msg, String[] info) {
                if (code == 0) {
                    paySuccess();
                    ToastUtil.show(WordUtil.getString(R.string.pay_pal_success));
                }
            }
        });
    }

    private void paySuccess() {
        CommonHttpUtil.getBalance(new HttpCallback() {
            @Override
            public void onSuccess(int code, String msg, String[] info) {
                if (code == 0 && info.length > 0) {
                    JSONObject obj = JSON.parseObject(info[0]);
                    String coin = obj.getString("coin");
                    mBalanceValue = Long.parseLong(coin);
                    mBalance.setText(coin);
                }
            }

            @Override
            public void onFinish() {
                if (mRefreshLayout != null) {
                    mRefreshLayout.setRefreshing(false);
                }
            }
        });
    }

    @Override
    public void payCancel() {
        ToastUtil.show(WordUtil.getString(R.string.pay_pal_cancel));
    }

    @Override
    public void payFail() {
        ToastUtil.show(WordUtil.getString(R.string.pay_pal_fail));
    }


    private void loadBannerAd() {
        // 计算 Banner 广告宽高，单位dp
        float screenWidth = ScreenDimenUtil.getInstance().getScreenWdith();
        float padding = DensityUtil.dp2px(15);
        float width = screenWidth - padding*2;
        float height = width / 6.4f; // 推荐宽高比6.4:1

        AdSdk.getInstance().loadBannerAd(this, "b1", mContainer, width, height,
                new AdSdk.BannerAdListener() {
                    @Override
                    public void onAdLoad(String id, AdSdk.BannerAd ad) {
                        Log.d(TAG, "BannerAd onAdLoad");
                        // 设置刷新频率，为0或30~120之间的整数，单位秒，0表示不自动轮播，默认30秒
                        ad.setRefreshInterval(30);
                        mBannerAd = ad;
                    }

                    @Override
                    public void onAdShow(String id) {
                        Log.d(TAG, "BannerAd onAdShow");
                    }

                    @Override
                    public void onAdClose(String id) {
                        Log.d(TAG, "BannerAd onAdClose");
                    }

                    @Override
                    public void onAdClick(String id) {
                        Log.d(TAG, "BannerAd onAdClick");
                    }

                    @Override
                    public void onError(String id, int code, String message) {
                        Log.d(TAG, "BannerAd onError: code=" + code + ", message=" + message);
                    }
                });
    }

    private void destroyBannerAd() {
        if (null != mBannerAd) {
            mBannerAd.destroy();
            mBannerAd = null;
        }
    }
}
